package ynu.edu.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.entity.DeliveryAddress;
import ynu.edu.repository.DeliveryAddressRepository;
import ynu.edu.service.UserService;

import java.util.List;

@Slf4j
@Service
public class DeliveryAddressService {

    @Autowired
    private DeliveryAddressRepository deliveryAddressRepository;

    @Autowired
    private UserService userService;

    private Integer getUserId(String userName) {
        return userService.getUserByName(userName).getUserId();
    }

    public List<DeliveryAddress> listByUserName(String userName) {
        if (userName == null) {
            throw new RuntimeException("userName不能为空");
        }
        Integer userId = getUserId(userName);
        return deliveryAddressRepository.findByUserId(userId);
    }

    public DeliveryAddress getById(Integer daId) {
        return deliveryAddressRepository.findById(daId)
                .orElseThrow(() -> new RuntimeException("配送地址不存在"));
    }

    @Transactional
    public int updateAddress(DeliveryAddress address) {
        DeliveryAddress existingAddress = getById(address.getDaId());
        existingAddress.setContactName(address.getContactName());
        existingAddress.setContactSex(address.getContactSex());
        existingAddress.setContactTel(address.getContactTel());
        existingAddress.setAddress(address.getAddress());
        deliveryAddressRepository.save(existingAddress);
        return 1;
    }

    @Transactional
    public int removeAddress(Integer daId) {
        deliveryAddressRepository.deleteById(daId);
        return 1;
    }

    @Transactional
    public int saveAddress(DeliveryAddress address) {
        try {
            if (address.getUserName() == null) {
                throw new RuntimeException("userName不能为空");
            }
            address.setUserId(getUserId(address.getUserName()));
            deliveryAddressRepository.save(address);
            return 1;
        } catch (Exception e) {
            log.error("Failed to save delivery address", e);
            return 0;
        }
    }
} 